<template>
  <!-- 更新应急演练计划 -->
  <base-breadcrumb>
    <a-card :bordered="false">
      <div class="page-header table-page-search-wrapper">
        <title-name :title="params.pageType === 'look' ? '信息详情' : '基本信息'" />
        <a-form-model
          ref="ruleForm"
          :model="formInfo"
          :rules="rules"
          :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
          :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
        >
          <a-row :gutter="24">
            <a-col :md="16" :sm="16">
              <a-form-model-item label="所属单位" prop="projectId">
                <span v-if="params.pageType === 'look'">{{ formInfo.branchComName + '/' + formInfo.projectName}}</span>
                <org-tree-select v-else
                                 v-model="formInfo.projectId"
                                 is-need-auth
                                 is-auto-select-first
                                 check-strictly
                                 :is-query-projec-detail="false"
                                 @select="selectOrg"
                ></org-tree-select>
              </a-form-model-item>
            </a-col>
<!--            <a-col :md="8" :sm="8">-->
<!--              <a-form-model-item label="所属分公司" prop="branchComId">-->
<!--                <span v-if="params.pageType === 'look'">{{ formInfo.branchComName }}</span>-->
<!--                <SelectSubCompany v-else placeholder="请选择" v-model="formInfo.branchComId"></SelectSubCompany>-->
<!--              </a-form-model-item>-->
<!--            </a-col>-->
<!--            <a-col :md="8" :sm="8">-->
<!--              <a-form-model-item label="所属项目" prop="project">-->
<!--                <span v-if="params.pageType === 'look'">{{ formInfo.projectName }}</span>-->
<!--                <SelectProject-->
<!--                  v-else-->
<!--                  placeholder="请选择"-->
<!--                  v-model="formInfo.project"-->
<!--                  :form="formInfo"-->
<!--                  :isClear="params.id == ''"-->
<!--                  keyValue="branchComId"-->
<!--                  @change="changeName()"-->
<!--                  labelInValue-->
<!--                ></SelectProject>-->
<!--              </a-form-model-item>-->
<!--            </a-col>-->
            <a-col :md="8" :sm="8">
              <a-form-model-item label="名称" prop="name">
                <span v-if="params.pageType === 'look'">{{ formInfo.name }}</span>
                <BaseInput v-else placeholder="请输入" v-model="formInfo.name" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>

    <a-card :bordered="false" class="mb20">
      <title-name title="应急演练计划表" />
      <div class="table-operateors mb20" v-if="params.pageType !== 'look'">
        <a-button
          type="primary"
          icon="plus"
          @click="
            openModa()
            visible = true
            isEdit = false
            modalData = {}
          "
          >添加计划项</a-button
        >
        <!-- 导入 -->
        <ExcelImportButton ref="excelImportButton" icon="import" class="ml12" @handleSubmit="handleSubmit" />
        <!-- 导出模板 -->
        <export-mould class="ml12" templateCode="安全演练计划模板.xlsx" icon="cloud-download"></export-mould>
      </div>
      <s-table
        :bordered="true"
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :showPagination="false"
      >
        <template slot="operator" slot-scope="text, record">
          <div v-if="params.pageType !== 'look'">
            <a
              class="base-btn"
              @click="
                openModa(record)
                visible = true
                isEdit = true
                modalData = record
              "
              >编辑</a
            >
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除?" @confirm="() => delItem(record)">
              <a>删除</a>
            </a-popconfirm>
            <!-- <a class="base-btn" @click="delItem(record)">删除</a> -->
          </div>
          <a v-else class="base-btn" @click="editRecord(record)">演练记录填写</a>
        </template>
      </s-table>
    </a-card>

    <div class="tool-btns page-btn-right-top" v-if="pageType !== 'look'">
      <a-button :loading="loading.DRAFT" class="ml20" type="primary" @click="submitForm('DRAFT')">保存</a-button>
      <a-button :loading="loading.SUBMITTED" class="ml20" type="primary" @click="submitForm('SUBMITTED')">提交</a-button>
      <a-button class="ml20" type="primary" @click="closeForm">关闭</a-button>
    </div>

    <div v-else class="tool-btns page-btn-right-top">
      <a-button class="ml20" type="primary" @click="closeForm">关闭</a-button>
    </div>

    <a-modal
      :title="isEdit ? '应急演练计划项编辑' : '应急演练控计划项添加'"
      :width="900"
      :visible="visible"
      @cancel="
        cancel()
        visible = false
        cancel()
      "
      @ok="
        submitModal()
        visible = false
      "
    >
      <a-form-model
        ref="ruleFormModal"
        :model="modalData"
        :rules="rulesModal"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col :md="12" :sm="12">
            <a-form-model-item label="应急演练名称" prop="name">
              <BaseInput placeholder="请输入" v-model="modalData.name" />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="演练方式" prop="drillMethodId">
              <a-select placeholder="请选择" v-model="modalData.drillMethodId">
                <a-select-option v-for="i in selectList" :key="i.id" :value="i.id">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="计划演练时间" prop="drillDate">
              <a-date-picker placeholder="请输入" v-model="modalData.drillDate" />
            </a-form-model-item>
          </a-col>

          <a-col :md="24" :sm="24">
            <a-form-model-item label="演练内容" prop="drillContent">
              <BaseTextarea placeholder="请输入" v-model="modalData.drillContent" />
            </a-form-model-item>
          </a-col>

          <a-col :md="24" :sm="24">
            <a-form-model-item label="演练所需器材" prop="reqEquip">
              <BaseTextarea placeholder="请输入" v-model="modalData.reqEquip" />
            </a-form-model-item>
          </a-col>

          <a-col :md="24" :sm="24">
            <a-form-model-item label="参与演练人员" prop="participants">
              <BaseTextarea placeholder="请输入" v-model="modalData.participants" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components'

import { getPlan, editPlan, addPlan, deletePlan } from '@/api/safetySupervision/emergencyDrill'
import { getSelectListByType } from '@/api/safetySupervision/common'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import ExportMould from '@/components/ExportMould' // 导出模板文件按钮

const columns = [
    {
        title: '应急演练名称',
        dataIndex: 'name',
        width: '10%',
        ellipsis: true,
    },
    {
        title: '演练方式',
        dataIndex: 'drillMethodDesc',
        width: '10%',
        ellipsis: true,
    },
    {
        title: '演练内容',
        dataIndex: 'drillContent',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '演练所需器材',
        dataIndex: 'reqEquip',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '计划演练时间',
        dataIndex: 'drillDate',
        width: '10%',
        ellipsis: true,
    },
    {
        title: '参与演练人员',
        dataIndex: 'participants',
        width: '20%',
        ellipsis: true,
    },
    {
        title: ' 操作',
        dataIndex: 'operator',
        scopedSlots: { customRender: 'operator' },
        width: '10%',
        ellipsis: true,
    },
]
export default {
    name:'a'+Date.now(),    components: {
        SelectSubCompany,
        SelectProject,
        STable,
    ExportMould
    },
    data() {
        this.columns = columns
        return {
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
            },
            pageType: 'add',
            params: {},
            selectList: [],
            isEdit: false,
            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目' }],
                name: [{ required: true, message: '请输入名称' }],
            },
            rulesModal: {
                name: [{ required: true, message: '请输入演练名称' }],
                drillMethodId: [{ required: true, message: '请选择演练方式' }],
                drillDate: [{ required: true, message: '请选择演练时间' }],
                drillContent: [{ required: true, message: '请输入演练内容' }],
                reqEquip: [{ required: true, message: '请输入演练所需器材' }],
                participants: [{ required: true, message: '参与演练人员' }],
            },
            visible: false,
            editIndex: -1,
            modalData: {},
            cacheItemVO: [],
            formInfo: {
                itemVO: [],
                name: '',
                projectName: "",
                branchComName: ""
            },
            queryParam: {},
            loadData: (parameter) => {
                const requestParameters = Object.assign({}, parameter, this.queryParam)
                return new Promise((resolve, reject) => {
                    resolve({
                        data: this.formInfo.itemVO,
                    })
                })
            },
        }
    },
    created() {
        this.params = this.$route.query
        this.pageType = this.$route.query.pageType

        console.log(this.$route)
        this.getPlan()
        this.getSelectList('10')
    },
    mounted() {
        if (this.pageType == 'look') {
            this.$route.meta.title = '应急演练计划查看'
        } else {
            console.log(this.params.id)
            this.$route.meta.title = this.params.id == '' ? '应急演练计划新增' : '应急演练计划编辑'
        }
    },

    methods: {
        selectOrg(val) {
          this.formInfo.branchComId = val[val.length - 2].orgId
          this.formInfo.project = {
            key: this.formInfo.projectId,
            label: val[val.length-1].projectName
          }
          this.changeName()
        },
        changeName() {
            this.$nextTick(() => {
                this.formInfo.name = this.formInfo.project.label + '应急演练计划'
                console.log(this.formInfo.name)
            })
        },
        cancel() {
            const newData = this.formInfo.itemVO
            const target = newData.filter((item) => this.modalData.key === item.key)[0]

      if (target) {
        Object.assign(target, this.cacheItemVO.filter((item) => this.modalData.key === item.key)[0])

        this.formInfo.itemVO = newData
      }
    },
    editRecord(record) {
      this.$router.push({
        name: 'UpdateEmergencyRecord',
        query: {
          id: record.id || '',
          pageType: 'edit',
          type: 'add',
        },
      })
    },
    openModa(record) {
      this.cacheItemVO = []
      this.cacheItemVO = this.formInfo.itemVO.map((item) => ({ ...item }))

      //   const newCacheData = [...this.cacheData1]
      // this.cacheModalData=record;
    },

    async getSelectList(type) {
      const [err, res] = await getSelectListByType({ type })
      if (!err) {
        this.selectList = res.data || []
      }
    },
    async deletePlan(params) {
      const [err, res] = await deletePlan(params)
      if (!err) {
        this.$message.success('删除成功')
        this.closeForm()
      }
    },
    async deleteDraft() {
      let obj = {
        id: this.params.id,
      }
      let that = this
      this.$confirm({
        title: '温馨提示',
        content: '确定是否删除数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          return that.deletePlan(obj)
        },
      })
    },
    submitModal() {
      let that = this
      this.$refs.ruleFormModal.validate((valid) => {
        if (valid) {
          console.log(this.modalData)
          if (typeof this.modalData.drillDate != 'string') {
            this.modalData.drillDate = this.modalData.drillDate.format('YYYY-MM-DD')
          }

          console.log(this.modalData)
          this.modalData.drillMethodDesc = this.selectList.filter(
            (item) => this.modalData.drillMethodId == item.id
          )[0].name

                    if (this.isEdit) {
                        Object.assign(
                            this.modalData,
                            this.formInfo.itemVO.filter((item) => this.modalData.key === item.key)[0]
                        )
                        console.log(this.formInfo)
                    } else {
                        this.modalData.key = this.formInfo.itemVO.length.toString()
                        this.formInfo.itemVO.push(this.modalData)
                    }
                    this.$refs.table.refresh(true)
                } else {
          this.$message.warning("请填写完所有必填项信息")
        }
            })
        },
    //     async getPlan() {
    //         if (this.$route.query.pageType === 'look') {
    //             this.rules = {}
    //         }
    //         const { id } = this.$route.query
    //         if (!id) return
    //         const params = {
    //             id,
    //         }
    //         const [err, res] = await getPlan(params)
    //         if (!err) {
    //             this.formInfo = {
    //                 ...this.formInfo,
    //                 ...res.data,
    //                 project: { key: res.data.projectId, lable: res.data.projectName },
    //             }
    //             // this.formInfo = {

    //             //     ...res.data,
    //             // }
    //             this.$refs.table.refresh(true)
    //         }
    //         console.log(this.formInfo)
    //         this.formInfo.itemVO.forEach((item, i) => {
    //             item.key = i.toString()
    //             if (item.drillMethod) {
    //                 item.drillMethodId = item.drillMethod.id
    //             }
    //             item.drillMethodIdName = item.drillMethod.name
    //         })
    //         console.log(this.formInfo)
    //       } else {
    //         this.modalData.key = this.formInfo.itemVO.length.toString()
    //         this.formInfo.itemVO.push(this.modalData)
    //       }
    //       this.$refs.table.refresh(true)
    //     }
    //   })
    // },
    async getPlan() {
      if (this.$route.query.pageType === 'look') {
        this.rules = {}
      }
      const { id } = this.$route.query
      if (!id) return
      const params = {
        id,
      }
      const [err, res] = await getPlan(params)
      if (!err) {
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
          project: { key: res.data.projectId, lable: res.data.projectName },
        }
        // this.formInfo = {

        //     ...res.data,
        // }
        this.$refs.table.refresh(true)
      }
      console.log(this.formInfo)
      this.formInfo.itemVO.forEach((item, i) => {
        item.key = i.toString()
        if (item.drillMethod) {
          item.drillMethodId = item.drillMethod.id
        }
        item.drillMethodDesc = item.drillMethod.name
      })
      console.log(this.formInfo)
    },
    delItem(data) {
      this.formInfo.itemVO.forEach((item, idx) => {
        if (item.key == data.key) {
          this.formInfo.itemVO.splice(idx, 1)
        }
      })
    },
    // 处理更新操作（新增、编辑）
    handleUpdate(type, data) {
      this.modalData = data
    },
    closeForm() {
      this.$multiTab.close(this.$route.fullpath)
    },
    submitForm(auditStatus) {
      let that = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (that.formInfo.itemVO.length == 0) {
            that.$message.warning('请添加计划项')
            return
          }

          this.initParams(auditStatus)
          if (this.params.id == '') {
            this.addPlan(auditStatus)
          } else {
            this.editPlan(auditStatus)
          }
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    initParams(auditStatus) {
      this.formInfo.projectId = this.formInfo.project.key
      this.loading[auditStatus] = true
      this.formInfo.auditStatus = auditStatus
      console.log(this.formInfo)
      // this.formInfo.itemVO.forEach((item) => {
      //     if (item.drillMethod) {
      //         item.drillMethodId = item.drillMethod.id
      //     }
      // })
      console.log(this.formInfo)
      this.formInfo.itemDTO = this.formInfo.itemVO
    },
    async addPlan(status) {
      const [err, res] = await addPlan(this.formInfo)
      if (!err) {
        this.$message.success('添加成功')

        this.closeForm()
      }
      this.loading[status] = false
    },
    async editPlan(status) {
      const [err, res] = await editPlan(this.formInfo)
      if (!err) {
        this.$message.success('修改成功')
        this.closeForm()
      }
      this.loading[status] = false
    },
    /**
     * 导入记录
     */
    handleSubmit(e) {
      let form = []
      for (let index in e) {
        form.push({})
        let keys = e[index]
        let listItem = form[index]
        // 校验excel的表头数量
        if (Object.keys(keys)?.length === 6) {
          // 校验excel的表头字段
          for (let i in this.importCheck) {
            let item = this.importCheck[i]
            if (!Object.keys(keys).includes(i)) {
              this.$message.warning(`${i}缺失`)
              return
            } else {
              listItem[item] = keys[i]
            }
          }
        } else {
          this.$message.warning('数据不完整')
          return
        }
      }
      this.formInfo.itemVO = this.formInfo.itemVO.concat(form)
      this.$refs.table.refresh(true)
    },
  },
}
</script>

<style lang="less" scoped>
.foot-btn {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
</style>
